package com.leyou.gateway.filters;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpCookie;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author mySun
 * @create 2021-07-29 16:13
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter {
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpCookie cookie = exchange.getRequest().getCookies().toSingleValueMap().get("LY_TOKEN");
        if(cookie == null){
            //用户未登录，放行
            return chain.filter(exchange);
        }

        String token = cookie.getValue();


        try {
            Payload payload = jwtUtils.parseJwt(token);
            UserDetail userDetail = payload.getUserDetail();

            jwtUtils.refresh(userDetail.getUsername());

            log.info("用户{}正在访问{}", userDetail.getUsername(), exchange.getRequest().getURI().getPath());
        } catch (Exception e) {
            // 解析失败，token有误
            log.info("用户未登录");
        }

        //放行
        return chain.filter(exchange);
    }
}
